package Thread;
class BlockingQueue{
    private String[] elems = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;
    private Object locker = new Object();
    public BlockingQueue(int capacity){
        elems = new String[capacity];
    }
    public String take() throws InterruptedException {
        //将return置于锁外,可以提高线程的执行效率.
        String s = null;
        //锁需要将if包裹
        synchronized (locker) {
            while (size == 0) {
                locker.wait();
            }
            s = elems[head];
            head++;
            if (head >= elems.length) {
                head = 0;
            }
            size--;
            locker.notify();
        }
            return s;

    }
    public void put(String elem) throws InterruptedException {
        //此时上锁应该全部上锁,如果不给if上锁的话,有可能第一个线程if判断后第二个线程紧接着判断,此时就会发生连续加两次的情况,使元素溢出
        synchronized (locker) {
            while (size >= elems.length) {
                locker.wait();
            }
                elems[tail] = elem;
                tail++;
                if (tail >= elems.length) {
                    tail = 0;
                }
                size++;
                locker.notify();
            }
        }
    }
public class ThreadDemo3 {
    public static void main(String[] args) {
        BlockingQueue queue = new BlockingQueue(6);
        Thread t1 = new Thread(() -> {
            int n = 0;
            while(true) {
                try {
                    queue.put(n + "");
                    System.out.println("生产元素" + n);
                    n++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    String s = queue.take();
                    System.out.println("消费元素"+s  );
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }

}
